package com.brkj.communityStudy;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.brkj.httpInterface.BaseAjaxParams;
import com.brkj.httpInterface.HttpInterface;
import com.brkj.httpInterface.NomalResult;
import com.brkj.main.R;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.MyApplication;
import com.brkj.util.PickPhoto;
import com.brkj.util.view.BaseActivity;
import com.brkj.util.view.BaseCoreActivity;
import com.brkj.util.view.WidgetAnim;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by colin.ding on 2014/5/27.
 */
public class ExperienceWriteActivity extends BaseActivity{
    private LinearLayout mainLayout;

    private List<EditText> textList = new ArrayList<EditText>();
    private List<ImageView> imageList = new ArrayList<ImageView>();
    private List<String> imageNameList = new ArrayList<String>();

    private PickPhoto pickPhoto;
    private EditText TitleEdit;
    private Button touchView;
    private Button chooseSystem;
    private TextView systemName;
    private LinearLayout systemView;
    private String systemID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setAnimType(RIGHT_ENTER_LEFT_EXT);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.experience_write);
        mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
        TitleEdit = (EditText) findViewById(R.id.TitleEdit);
        touchView = (Button) findViewById(R.id.touchView);
        chooseSystem = (Button) findViewById(R.id.chooseSystem);
        systemName = (TextView) findViewById(R.id.systemName);
        systemView = (LinearLayout) findViewById(R.id.systemView);

        chooseSystem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                systemView.setVisibility(View.VISIBLE);
            }
        });
        SystemStruct systemStruct = new SystemStruct(this, new SystemStruct.SystemStructItemClick() {
            @Override
            public void onClick(int topicID, String name) {
                systemID = Integer.toString(topicID);
                systemName.setText(name);
                systemView.setVisibility(View.GONE);
            }
        });

        systemView.addView(systemStruct.getView());

        touchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(textList.size()>0){
                    textList.get(textList.size()-1).setFocusable(true);
                    textList.get(textList.size()-1).setFocusableInTouchMode(true);
                    textList.get(textList.size()-1).requestFocus();
                    textList.get(textList.size()-1).requestFocusFromTouch();
                }

            }
        });


        initTitle();
        initPickPhoto();
        addEdit();

    }



    private void initTitle() {

        setReturnBtn();
        setActivityTitle("写经验");
        setRightBtn(R.drawable.send_selector, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });

        findViewById(R.id.insertImage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickPhoto.pick();
            }
        });
    }

    private void initPickPhoto(){
       pickPhoto = new PickPhoto(this, new PickPhoto.PickResult() {

            @Override
            public void doWhat(Bitmap photo) {

                imageList.get(imageList.size()-1).setImageBitmap(photo);

                addEdit();

                // 创建 GUID 对象
                UUID uuid = UUID.randomUUID();
                // 得到对象产生的ID
                String imageName = uuid.toString();
                // 转换为大写
                imageName = imageName.toUpperCase();

                imageNameList.add(imageName);

                try {
                    BaseAjaxParams params = new BaseAjaxParams();
                    params.put(HttpInterface.HIF_ExpSubmitImage.params.imageFIle, pickPhoto.GetImageFile());
                    params.put(HttpInterface.HIF_ExpSubmitImage.params.fileName, imageName);

                    FinalHttp fh = new FinalHttp();
                    fh.post(HttpInterface.HIF_ExpSubmitImage.address, params, new AjaxCallBack() {
                        @Override
                        public void onSuccess(Object o) {
                            super.onSuccess(o);
                        }
                    });

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });

        pickPhoto.setImgSavePath(MyApplication.myInfo.getMyHeadImgPath());
        pickPhoto.setPickParam(16, 9, 320, 180);
    }


    private void addEdit() {
        View cellView = LayoutInflater.from(this).inflate(R.layout.experience_write_cell, null);
        EditText text = (EditText) cellView.findViewById(R.id.text);
        ImageView image = (ImageView) cellView.findViewById(R.id.image);

        textList.add(text);
        imageList.add(image);

        mainLayout.addView(cellView);
    }

    private void submit() {

        if(WidgetAnim.checkIfEmpty(this, TitleEdit)){
            return;
        }

        if((systemID== null) || (systemID.equals(""))){
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_right_left);
            chooseSystem.startAnimation(animation);
            showToast("请选择体系");
            return;
        }

        if(WidgetAnim.checkIfEmpty(this, textList.get(0))){
            return;
        }

        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HttpInterface.HIF_WriteExpSubmit.params.UserID, MyApplication.myUserID);
        params.put(HttpInterface.HIF_WriteExpSubmit.params.Title, TitleEdit.getText().toString());
        params.put(HttpInterface.HIF_WriteExpSubmit.params.SystemID, systemID);


        JSONArray jsonArray = new JSONArray();
        for(int i=0; i<textList.size(); i++ ){

            try {
                JSONObject jsonObject =  new JSONObject();
                jsonObject.put("Text", textList.get(i).getText().toString());
                if(imageNameList.size()>i){
                    jsonObject.put("fileName", imageNameList.get(i));
                }else{
                    jsonObject.put("fileName", "");
                }


                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        params.put(HttpInterface.HIF_WriteExpSubmit.params.Content, jsonArray.toString());

        FinalHttp fh = new FinalHttp();

        fh.post(HttpInterface.HIF_WriteExpSubmit.address, params, new MyAjaxCallBack<Object>((BaseCoreActivity)this) {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);

                if(NomalResult.doResult(o, ExperienceWriteActivity.this)){
                    showToast("发表成功");
                    finish();
                }
            }
        });

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        pickPhoto.onActivityResult(requestCode, resultCode, data);
    }
}

